package com.code.petapp.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import android.widget.Toast;

import com.code.petapp.R;
import com.code.petapp.activity.OrderActivity;
import com.code.petapp.activity.PersonActivity;
import com.code.petapp.adapter.HomeAdapter;
import com.code.petapp.bean.AdoptBean;
import com.code.petapp.bean.AnimalBean;
import com.code.petapp.bean.BaseBean;
import com.code.petapp.bean.OrderBean;
import com.code.petapp.databinding.FragmentHomeBinding;
import com.code.petapp.http.HttpListener;
import com.code.petapp.util.AdoptUtils;
import com.code.petapp.util.AnimalUtils;
import com.code.petapp.util.OrderUtils;
import com.code.petapp.util.SPCommonUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.annotations.Nullable;

public class HomeFragment extends Fragment implements HomeAdapter.OnItemClickListener {
    private RecyclerView recyclerView;//声明RecyclerView
    private HomeAdapter homeAdapter;//声明适配器
    private boolean isGetData = false;
    FragmentHomeBinding binding;
    private List<AnimalBean> list;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View view = binding.getRoot();
        changeMsg();
        list = new ArrayList<>();
        load("");
        search();
        recyclerView = binding.recView;
        homeAdapter = new HomeAdapter(getContext(), list);
        homeAdapter.setOnItemClickListener(this);
        GridLayoutManager manager = new GridLayoutManager(getContext(), 2);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(homeAdapter);
        return view;
    }
    @Override
    public void onResume() {//每次重进页面都会刷新数据
        if (!isGetData) {
            //   这里可以做网络请求或者需要的数据刷新操作
            load("");
            isGetData = true;
        }
        super.onResume();
    }
    @Override
    public void onPause() {
        super.onPause();
        isGetData = false;
    }
    private void changeMsg() {
        if(SPCommonUtils.getInstance().getEmail()==""||SPCommonUtils.getInstance().getPhone()==""){
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setIcon(R.drawable.icon);
            builder.setTitle("身份信息不完整");
            builder.setMessage("是否前往账号管理页面填写身份信息？");
            builder.setPositiveButton("前往",
                            (DialogInterface dialog, int arg1) -> {
                                dialog.dismiss();
                                startActivity(new Intent(getActivity(), PersonActivity.class));
                            })
                    .setNegativeButton("取消",
                            (DialogInterface dialog, int arg1) -> {
                                dialog.dismiss();
                            });
            builder.create().show();
        }
    }
    private void search(){
        binding.searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                searchData(s);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                searchData(s);
                return false;
            }
        });
    }
    private void searchData(String s){
        load(s);
    }

    private void load(String name) {
        AnimalUtils.selectAll(SPCommonUtils.getInstance().getToken(), name,new HttpListener<>() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void success(@Nullable ArrayList<AnimalBean> beanList) {
                Log.d("ZZ","beanList:"+beanList);
                list.clear();
                list.addAll(beanList);
                homeAdapter.notifyDataSetChanged();
            }
            @Override
            public void error(int code, @Nullable String error) {
                Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onClick(View parent, int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setIcon(R.drawable.icon);
        builder.setTitle("饲养员描述");
        builder.setMessage('“'+list.get(position).getDescr()+'”');
        builder.setPositiveButton("领养",
                        (DialogInterface dialog, int arg1) -> {
                            dialog.dismiss();
                            AnimalBean animalBean=new AnimalBean();
                            int id=list.get(position).getId();
                            animalBean.setId(id);
                            animalBean.setStatus("已领养");
                            AnimalUtils.update(SPCommonUtils.getInstance().getToken(), animalBean, new HttpListener<>() {
                                @Override
                                public void success(String data) {
                                    add(id);
                                }

                                @Override
                                public void error(int code, String error) {
                                    Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show();
                                }});
                        })
                .setNegativeButton("返回",
                        (DialogInterface dialog, int arg1) -> {
                            dialog.dismiss();
                        });
        builder.create().show();
    }
    //同步给adopt
    private void add(int id) {
        AdoptBean adoptBean = new AdoptBean();
        adoptBean.setAnimalId(id);
        adoptBean.setUserId(SPCommonUtils.getInstance().getUserId());
        AdoptUtils.add(SPCommonUtils.getInstance().getToken(), adoptBean, new HttpListener<>() {
            @Override
            public void success(String object) {
                load("");
                Toast.makeText(getContext(), "恭喜您成为它的主人！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void error(int code, String error) {
                Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show();
            }
        });
    }
}